package com.course.server.service;

import com.course.server.domain.Section;
import com.course.server.domain.SectionExample;
import com.course.server.dto.SectionDTO;
import com.course.server.dto.PageDTO;
import com.course.server.enums.SectionChargeEnum;
import com.course.server.mapper.SectionMapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class SectionService {

    @Resource
    private SectionMapper sectionMapper;

    public void list(PageDTO pageDTO){

        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        //分页规则：调用startPage方法后，下面遇到的第一条select语句会进行分页
        SectionExample sectionExample = new SectionExample();

        sectionExample.setOrderByClause("sort asc");

        List<Section> sections = sectionMapper.selectByExample(sectionExample);

        PageInfo<Section> pageInfo = new PageInfo<>(sections);

        pageDTO.setTotal(pageInfo.getTotal());

        ArrayList<SectionDTO> sectionDTOList = new ArrayList<>();

        for (int i = 0; i < sections.size(); i++) {
            Section section = sections.get(i);
            SectionDTO sectionDTO = new SectionDTO();
            BeanUtils.copyProperties(section, sectionDTO);
            sectionDTOList.add(sectionDTO);
        }
        pageDTO.setList(sectionDTOList);
    }

    public void save(SectionDTO sectionDTO){
        Section section = CopyUtil.copy(sectionDTO, Section.class);
        if (StringUtils.isEmpty(sectionDTO.getId())){
            //前端没有带过来id，则是新增
            this.insert(section);
        }else{
            this.update(section);
        }
    }

    private void insert(Section section){
        Date now = new Date();
        section.setCreatedAt(now);
        section.setUpdatedAt(now);
        section.setId(UuidUtil.getShortUuid());
        section.setCharge(SectionChargeEnum.CHARGE.getCode());
        sectionMapper.insert(section);
    }

    private void update(Section section){
        Date now = new Date();
        section.setUpdatedAt(now);
        sectionMapper.updateByPrimaryKey(section);
    }

    public void delete(String id){
        sectionMapper.deleteByPrimaryKey(id);
    }


}
